package com.ruoyi.aitcommon.utils;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ruoyi.aitapp.utils.APPRuntimeManager;
import com.ruoyi.aitapp.vo.LicenseInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Component
public class LicenseUtils {
    @Autowired
    APPRuntimeManager appRuntimeManager;
    private final String REQUEST_FILE = "license.req";
    private final String PERMIT_FILE = "license.lic";

    /**
     * 依据许可信息,创建许可文件
     * @param reqContent 许可字符串
     * @return
     */
    public File createPermitFile(String reqContent,int maxUserNum,String startDate,String endDate,String path) throws Exception {
        // 许可申请解码
        final String decodedString = Base64Utils.decode(reqContent);
        JSONObject jsonObject = JSONObject.parseObject(decodedString);
        // 构造许可文件信息
        final String cpuid = jsonObject.getJSONObject("CPU Info").getString("Processor ID");
        ExceptionUtils.checkBlankOrUndefined(cpuid,"CPU ID不能为空");

        LicenseInfoVO licenseInfoVO = new LicenseInfoVO();
        licenseInfoVO.setCpuid(cpuid);
        licenseInfoVO.setStartDate(DateUtil.parseDate(startDate).toDateStr());
        licenseInfoVO.setEndDate(DateUtil.parseDate(endDate).toDateStr());
        licenseInfoVO.setMaxUserNum(maxUserNum);

        // base64编码,加密
        String encodedLicense = Base64Utils.encode(JSONUtils.toJSON(licenseInfoVO).toString());
        final String encrypt = AesUtils.encrypt(encodedLicense);
        final File file = FileUtils.writeFile(path, encrypt);
        return file;
    }

    /**
     * 获取许可文件信息
     * 校验许可是否有效
     * @return
     */
    public LicenseInfoVO getLicenseInfo() throws Exception {
//        获取许可文件信息
        final String content = FileUtils.readFileLines(PERMIT_FILE);
//        解密,解码
        final String decrypt = AesUtils.decrypt(content);
        final String decode = Base64Utils.decode(decrypt);
        LicenseInfoVO licenseInfoVO = JSONUtils.toJavaObject(decode, LicenseInfoVO.class);
//        获取当前用户数
        licenseInfoVO.setCurUserNum(appRuntimeManager.getActiveUserCnt());
//        处理返回
        return licenseInfoVO;
    }
    /**
     * 验证许可信息
     * @return
     */
    public void validateLicense() throws Exception {
//        获取许可文件信息
        final LicenseInfoVO licenseInfoVO = this.getLicenseInfo();
        String storedCpuId = licenseInfoVO.getCpuid();
//        获取当前硬件信息
        String currentCpuId = HardwareInfoManager.getCPUID();
//        对比
        if(!storedCpuId.equals(currentCpuId)){
            throw new Exception("许可信息失效");
        }
        if(licenseInfoVO.getUsableDateNum()<0){
            ExceptionUtils.throwException(null,"超过许可使用数,过期天数[{}]",licenseInfoVO.getUsableDateNum()*-1);
        }
        if(licenseInfoVO.getUsableUserNum()<0){
            ExceptionUtils.throwException(null,"超过许可使用数,超过许可数[{}]",licenseInfoVO.getUsableUserNum()*-1);
        }
    }

    /**
     * 写入许可文件
     * @param inputStream
     * @return
     */
    public File writePermitFile(InputStream inputStream) throws Exception {
        return FileUtils.writeFile(PERMIT_FILE, inputStream);
    }
    /**
     * 获取许可申请信息
     * @return
     */
    public File getRequestFile() throws Exception {
        // --- 写入文件 ---
//        final String infoStr = HardwareInfoManager.getAllInfo().toString(SerializerFeature.PrettyFormat);
        final String infoStr = HardwareInfoManager.getAllInfo().toString();
        // 使用 Base64 编码
        String encodedString = Base64Utils.encode(infoStr);
        final File file = FileUtils.writeFile(REQUEST_FILE, encodedString); // 格式化缩进输出
        return file;
    }
}
